package com.adcc.loadsheet.billing.validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import java.lang.reflect.ParameterizedType;

/**
 * Created by zhaoml on 2020/4/7.
 */
public abstract class ValidatorAdapter<T> extends BasisValidator implements Validator {

    @Autowired
    private ValidationService validationService;

    private Class<T> entityClass;

    @SuppressWarnings("unchecked")
    public ValidatorAdapter() {
        this.entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return entityClass.equals(clazz);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void validate(Object target, Errors errors) {
        T entity = (T) target;
        validationService.validate(entity, errors);
        customValidate(entity, errors);
    }

    public void customValidate(T target, Errors errors) {
    }
}